package cc.mrbird.febs.server.referral.utils;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.codec.binary.Base64;

public class WXCore {
    private static final String WATERMARK = "watermark";
    private static final String APPID = "appid";
    /**
     * 解密
     * @param appId   --- 你的appId
     * @param encryptedData --- 加密的数据
     * @param sessionKey --- 密钥（session_key）
     * @param iv
     * @return
     */
    public static String decrypt(String appId, String encryptedData, String sessionKey, String iv){
        String result = "";
        try {
            AES aes = new AES();
            byte[] resultByte = aes.decrypt(Base64.decodeBase64(encryptedData), Base64.decodeBase64(sessionKey), Base64.decodeBase64(iv));
            if(null != resultByte && resultByte.length > 0){
                result = new String(WxPKCS7Encoder.decode(resultByte));
                JSONObject jsonObject = JSONObject.parseObject(result);
                String decryptAppid = jsonObject.getJSONObject(WATERMARK).getString(APPID);
                if(!appId.equals(decryptAppid)){
                    result = "";
                }
            }
        } catch (Exception e) {
            result = "";
            e.printStackTrace();
        }
        return result;
    }

    public static void main(String[] args) {
        String result = WXCore.decrypt("wx1f6f5be8dc927438",
                "I1tJAEcGGmOeOIE+y4SneHa0WI24chTuTCuYSRbPXG/01roaiPXDonJJWOFsdxcx6xUBJNjg8ea2HPPad3CkiA6hznhgTglwGPlnVEPdrs1N6u0AJJ2GjzyoQf1g7rGRI26NXeupXExsBWRxuNBduMkqJZRrNiu60SEsx/3A+zZ1GlutVxZPgYL4wnP52rtS3nYEoodZrZtvBtR6JgnrHQ==",
                "J4OSCKkGJyT\\/9hcUq8VDjg==",
                "pAZPSzTSE6c124byFQIIPg==");
        JSONObject jsonObject = JSONObject.parseObject(result);
        //防止空指针异常
        if(jsonObject!=null) {
            //获取的该手机号并不一定为非空，所以后面需要判断phone是否为null或者""
            String phone = jsonObject.getString("phoneNumber");
            System.out.println(phone);
        }
    }
}
